<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="header-content">
        <div class="header-left">
          <img src="/src/assets/ai-avatar.png" class="ai-logo" alt="AI智能助手" />
          <div class="header-info">
            <h2>AI智能助手</h2>
            <span class="status">
              <span class="status-dot"></span>
              在线服务中
            </span>
          </div>
        </div>
        <div class="header-right">
          <a-tooltip title="清空对话">
            <a-button type="text" class="action-btn" @click="clearMessages">
              <template #icon><DeleteOutlined /></template>
            </a-button>
          </a-tooltip>
        </div>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messageContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-wrapper" :class="[message.role]"
      >
        <div class="message-avatar">
          <img
            :src="
              message.role === 'assistant'
                ? aiAvatar
                : loginUserStore.loginUser.userAvatar
                  ? IMAGE_PREFIX + loginUserStore.loginUser.userAvatar
                  : defaultAvatar
            "
            :alt="message.role"
          />
        </div>

        <div class="message-content-wrapper">
          <div class="message-info">
            <span class="sender-name">{{ message.role === 'assistant' ? 'AI助手' : '我' }}</span>
            <span class="message-time">{{ formatTime(message.createTime) }}</span>
          </div>
          <template v-if="message.role === 'assistant' && message.content === ''">
            <div class="message-bubble waiting">
              <span class="dot-typing"> <span>.</span><span>.</span><span>.</span> </span>
            </div>
          </template>
          <template v-else>
            <div class="message-bubble">
              <template v-for="(block, idx) in parseAIContent(message.content)" :key="idx">
                <template v-if="block.type === 'think' && block.value.trim()">
                  <div class="ai-think-header">
                    <span class="ai-think-icon">🧠</span>
                    <span class="ai-think-title">深度思考</span>
                  </div>
                  <div class="ai-think-card">{{ block.value }}</div>
                </template>
                <MdPreview
                  v-else-if="block.type === 'text' && block.value.trim()"
                  :model-value="block.value"
                />
              </template>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-footer">
      <div class="input-container">
        <div class="input-left">
          <!-- 预设问题列表 -->
          <div class="quick-questions-wrapper">
            <a-tooltip title="点击查看常见问题">
              <a-button type="text" class="toggle-btn" @click="showQuestions = !showQuestions">
                <template #icon>
                  <QuestionCircleOutlined
                    :style="{ color: showQuestions ? '#1677ff' : '#64748b' }"
                  />
                </template>
              </a-button>
            </a-tooltip>
            <div class="quick-questions" v-if="showQuestions && commonQuestions.length > 0">
              <div class="quick-questions-title">
                <span>常见问题</span>
                <a-tooltip title="点击获取更多问题">
                  <a-button type="link" size="small" class="refresh-btn" @click="fetchQuestions">
                    <template #icon><SyncOutlined :spin="false" class="refresh-icon" /></template>
                    没想要的问题？换一批
                  </a-button>
                </a-tooltip>
              </div>
              <div class="quick-questions-list">
                <div
                  v-for="(question, index) in commonQuestions"
                  :key="index"
                  class="question-item"
                  @click="handleQuestionClick(question)"
                >
                  <span class="question-index">{{ index + 1 }}.</span>
                  <a-tooltip :title="question" v-if="question.length > 25">
                    <span class="question-text">{{ question.slice(0, 25) }}...</span>
                  </a-tooltip>
                  <span class="question-text" v-else>{{ question }}</span>
                </div>
              </div>
            </div>
          </div>
          <a-textarea
            v-model:value="inputMessage"
            :auto-size="{ minRows: 1, maxRows: 4 }"
            placeholder="输入您的问题，按Enter发送..."
            @keypress.enter.prevent="handleSend"
            class="message-input"
          />
        </div>
        <div class="input-actions">
          <a-button type="primary" :loading="sending" @click="handleSend" class="send-button">
            发送
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  defineOptions({ name: 'AIChatPage' })
  import { ref, onMounted, nextTick } from 'vue'
  import { message } from 'ant-design-vue'
  import {
    DeleteOutlined,
    QuestionCircleOutlined,
    SyncOutlined,
  } from '@ant-design/icons-vue'
  import dayjs from 'dayjs'
  import MarkdownIt from 'markdown-it'
  import 'highlight.js/styles/github.css'
  import { MdPreview } from 'md-editor-v3'
  import 'md-editor-v3/lib/preview.css'
  import { getQuestionsUsingGet, getChatConstantUsingGet } from '@/api/aijiekou'
  import { useLoginUserStore } from '@/stores/useLoginUserStore'
  import aiAvatar from '@/assets/ai-客服.svg'
  import { IMAGE_PREFIX } from '@/config/constants'

  // 默认头像
  const defaultAvatar = '/src/assets/default_avatar.png'

  // 初始化markdown-it，重写代码块渲染为CodeBlock组件
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    breaks: true,
    highlight: function () {
      // 不直接高亮，交给CodeBlock组件
      return ''
    },
  })

  // 自定义代码块渲染
  md.renderer.rules.fence = (tokens, idx) => {
    const token = tokens[idx]
    const code = token.content
    const lang = token.info.trim()
    // 渲染为CodeBlock组件
    return `<CodeBlock code="${encodeURIComponent(code)}" lang="${lang}" />`
  }

  // 将Markdown文本转换为HTML
  // const renderMarkdown = (content: string) => content.trim()

  // 定义消息类型
  interface ChatMessage {
    role: 'user' | 'assistant'
    content: string
    createTime: string
    done: boolean
  }

  const loginUserStore = useLoginUserStore()
  // const userAvatarUrl = computed(() => {
  //   return `https://fy-space-1333414113.cos.ap-beijing.myqcloud.com${loginUserStore.loginUser.userAvatar}`
  // })

  // 消息列表
  const messages = ref<ChatMessage[]>([])

  // 初始化消息列表
  const initMessages = () => {
    // 尝试从sessionStorage获取历史消息
    const cachedMessages = sessionStorage.getItem('aiAssistantMessages')
    if (cachedMessages) {
      messages.value = JSON.parse(cachedMessages)
    } else {
      // 如果没有缓存，设置默认欢迎消息
      messages.value = [
        {
          role: 'assistant',
          content: '您好！我是AI助手，请问有什么我可以帮您的吗？',
          createTime: new Date().toISOString(),
          done: true,
        },
      ]
    }
  }

  // 更新消息缓存
  const updateMessageCache = () => {
    sessionStorage.setItem('aiAssistantMessages', JSON.stringify(messages.value))
  }

  const inputMessage = ref('')
  const sending = ref(false)
  const messageContainer = ref<HTMLElement | null>(null)

  // 预设问题列表
  const commonQuestions = ref<string[]>([])
  const showQuestions = ref(false)

  // 获取预设问题列表
  const fetchQuestions = async () => {
    try {
      const res = await getQuestionsUsingGet()
      if (res.code === 200) {
        commonQuestions.value = res.data
      }
    } catch {
      message.error('获取预设问题失败')
    }
  }

  // 处理预设问题点击
  const handleQuestionClick = async (question: string) => {
    try {
      const res = await getChatConstantUsingGet({ question })
      if (res.code === 200) {
        // 添加用户问题
        messages.value.push({
          role: 'user',
          content: question,
          createTime: new Date().toISOString(),
          done: true,
        })

        // 添加预设答案
        messages.value.push({
          role: 'assistant',
          content: res.data,
          createTime: new Date().toISOString(),
          done: true,
        })

        updateMessageCache()
        await scrollToBottom()
      }
    } catch {
      message.error('获取答案失败')
    }
  }

  // 格式化时间
  const formatTime = (time: string) => {
    return dayjs(time).format('HH:mm')
  }

  // 滚动到底部
  const scrollToBottom = async () => {
    await nextTick()
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  }

  // 清空对话
  const clearMessages = () => {
    if (sending.value) {
      message.warning('请等待当前回复完成')
      return
    }
    messages.value = [
      {
        role: 'assistant',
        content: '您好！我是AI助手，请问有什么我可以帮您的吗？',
        createTime: new Date().toISOString(),
        done: true,
      },
    ]
    updateMessageCache()
  }

  // 处理发送消息
  const handleSend = async () => {
    const userInput = inputMessage.value.trim()
    if (!userInput) {
      message.warning('请输入消息内容')
      return
    }

    if (sending.value) return
    sending.value = true

    // 添加用户消息
    messages.value.push({
      role: 'user',
      content: userInput,
      createTime: new Date().toISOString(),
      done: true,
    })

    updateMessageCache()

    // 清空输入框
    inputMessage.value = ''
    await scrollToBottom()

    // 添加AI响应消息占位
    const aiMessage: ChatMessage = {
      role: 'assistant',
      content: '',
      createTime: new Date().toISOString(),
      done: false,
    }

    messages.value.push(aiMessage)
    updateMessageCache()

    try {
      const url = new URL(`http://localhost:8634/aichat/fc-chat`, window.location.origin)
      url.searchParams.append('question', userInput)

      const response = await fetch(url, {
        method: 'GET',
        headers: {
          Accept: 'text/html',
        },
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('Response body is null')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let accumulatedContent = ''

      while (true) {
        const { value, done } = await reader.read()
        if (done) break

        const text = decoder.decode(value)
        accumulatedContent += text

        await nextTick(() => {
          const updatedMessage = {
            ...aiMessage,
            content: accumulatedContent,
          }
          const lastIndex = messages.value.length - 1
          messages.value.splice(lastIndex, 1, updatedMessage)
        })
        await scrollToBottom()
      }
    } catch (error) {
      console.error('Error:', error)
      message.error('发送消息失败')
      messages.value.pop()
    } finally {
      sending.value = false
      // 这里要强制更新最后一条 assistant 消息的 done 字段，并去除首尾空行和空格，防止 markdown-it 渲染多余 <p>
      const lastIndex = messages.value.length - 1
      if (lastIndex >= 0 && messages.value[lastIndex].role === 'assistant') {
        let content = messages.value[lastIndex].content
        // 去除首尾多余空行和空格
        content = content.replace(/^[\s\n]+|[\s\n]+$/g, '')
        messages.value[lastIndex] = {
          ...messages.value[lastIndex],
          content,
          done: true,
        }
      }
      await scrollToBottom()
    }
  }

  // 处理AI回复内容，分离<think>块和普通内容，支持未闭合流式输出
  function parseAIContent(content: string) {
    const result: { type: 'think' | 'text'; value: string }[] = []
    const thinkReg = /<think>([\s\S]*?)<\/think>/g
    let lastIndex = 0
    let match
    while ((match = thinkReg.exec(content)) !== null) {
      if (match.index > lastIndex) {
        result.push({ type: 'text', value: content.slice(lastIndex, match.index) })
      }
      result.push({ type: 'think', value: match[1].trim() })
      lastIndex = thinkReg.lastIndex
    }
    // 检查是否有未闭合的 <think>
    const openIdx = content.lastIndexOf('<think>')
    const closeIdx = content.lastIndexOf('</think>')
    if (openIdx > closeIdx) {
      // 有未闭合的 <think>
      result.push({ type: 'think', value: content.slice(openIdx + 7) })
    } else if (lastIndex < content.length) {
      result.push({ type: 'text', value: content.slice(lastIndex) })
    }
    return result
  }

  onMounted(() => {
    initMessages()
    scrollToBottom()
    fetchQuestions()
  })
</script>

<style scoped>
  .chat-container {
    height: calc(100vh - 64px);
    display: flex;
    flex-direction: column;
    background: var(--theme-background);
    position: relative;
    transition: all 0.3s ease;
  }

  .chat-header {
    padding: 16px 24px;
    background: var(--theme-surface);
    border-bottom: 1px solid var(--theme-border);
    position: fixed;
    top: 64px;
    left: 0;
    right: 0;
    z-index: 10;
    box-shadow: 0 2px 4px var(--theme-shadow);
    transition: all 0.3s ease;
  }

  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .ai-logo {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  .header-info {
    display: flex;
    flex-direction: column;
  }

  .header-info h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--theme-text);
    transition: color 0.3s ease;
  }

  .status {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: var(--theme-textSecondary);
    margin-top: 4px;
    transition: color 0.3s ease;
  }

  .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--theme-primary);
    position: relative;
    transition: background 0.3s ease;
  }

  .status-dot::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: inherit;
    animation: pulse 2s infinite;
  }

  .action-btn {
    color: var(--theme-textSecondary);
    transition: all 0.3s;
  }

  .action-btn:hover {
    color: var(--theme-primary);
    background: var(--theme-background);
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    position: relative;
    background: var(--theme-background);
    padding-bottom: 90px;
    padding-top: 100px;
    scroll-behavior: smooth;
    height: 100%;
    z-index: 1;
    transition: all 0.3s ease;
  }

  .message-wrapper {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;
    padding-left: 14px;
    padding-right: 14px;
  }

  .message-wrapper.user {
    flex-direction: row-reverse;
  }

  .message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    overflow: hidden;
    flex-shrink: 0;
    margin-right: 0;
    margin-left: 0;
  }

  .message-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .message-content-wrapper {
    flex: 1;
    max-width: 85%;
    display: flex;
    flex-direction: column;
  }

  .user .message-content-wrapper {
    align-items: flex-end;
  }

  .message-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    width: 100%;
  }

  .user .message-info {
    flex-direction: row-reverse;
  }

  .sender-name {
    font-size: 13px;
    font-weight: 600;
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }

  .message-time {
    font-size: 12px;
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }

  .message-bubble {
    border-radius: 11px !important;
    background: var(--theme-surface);
    box-shadow: 0 2px 12px var(--theme-shadow);
    max-width: 92%;
    min-width: 60px;
    width: fit-content;
    margin-left: 5px;
    margin-right: 5px;
    padding: 1px 11px;
    display: flex;
    flex-direction: column;
    gap: 0px;
    z-index: 1 !important;
    transition: all 0.3s ease;
  }

  .message-text {
    border-radius: 18px !important;
    padding: 12px 18px;
    font-size: 15px;
    line-height: 1.7;
    background: var(--theme-surface);
    word-break: break-word;
    transition: all 0.3s ease;
  }

  .user .message-text {
    background: var(--theme-primary);
    color: var(--theme-surface);
    font-size: 15px;
    line-height: 1.8;
    border: none;
    box-shadow: 0 2px 8px var(--theme-shadow);
  }

  .thinking {
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }

  .thinking span {
    font-size: 18px;
    margin: 0 1px;
  }

  .thinking span:nth-child(2) {
    animation-delay: 0.2s;
  }

  .thinking span:nth-child(3) {
    animation-delay: 0.4s;
  }

  @keyframes thinking {
    0%,
    60%,
    100% {
      transform: translateY(0);
      opacity: 0.4;
    }
    30% {
      transform: translateY(-4px);
      opacity: 1;
    }
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
      opacity: 0.8;
    }
    70% {
      transform: scale(2.5);
      opacity: 0;
    }
    100% {
      transform: scale(1);
      opacity: 0;
    }
  }

  .chat-footer {
    padding: 16px 24px;
    background: var(--theme-background);
    border-top: 1px solid var(--theme-border);
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    transition: all 0.3s ease;
  }

  .input-container {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    gap: 12px;
    align-items: flex-end;
    padding: 0 24px;
  }

  .input-left {
    position: relative;
    flex: 1;
    display: flex;
    align-items: flex-end;
  }

  .quick-questions-wrapper {
    position: relative;
    margin-right: 8px;
  }

  .toggle-btn {
    padding: 8px;
    height: 42px;
    width: 42px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid var(--theme-border);
    border-radius: 10px;
    background: var(--theme-surface);
    transition: all 0.3s;
  }

  .toggle-btn:hover {
    background: var(--theme-background);
    border-color: var(--theme-primary);
  }

  .message-input {
    flex: 1;
    border-radius: 12px;
    resize: none;
    font-size: 14px;
    padding: 12px 16px;
    border-color: var(--theme-border);
    background: var(--theme-surface);
    transition: all 0.3s;
  }

  .message-input:hover {
    border-color: var(--theme-primary);
    background: var(--theme-background);
  }

  .message-input:focus {
    border-color: var(--theme-primary);
    background: var(--theme-surface);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  }

  .send-button {
    height: 42px;
    padding: 0 24px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    background: var(--theme-primary);
    color: var(--theme-surface);
    border-color: var(--theme-primary);
  }

  .send-button:not(:disabled):hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px var(--theme-shadow);
    background: var(--theme-secondary);
  }

  :deep(.ant-input) {
    border-radius: 12px;
  }

  :deep(.ant-btn) {
    border-radius: 10px;
  }

  /* 预设问题样式 */
  .quick-questions {
    position: absolute;
    bottom: calc(100% + 8px);
    left: 0;
    background: var(--theme-surface);
    border-radius: 8px;
    padding: 8px 0;
    box-shadow: 0 2px 12px var(--theme-shadow);
    border: 1px solid var(--theme-border);
    width: 300px;
    z-index: 1000;
    transition: all 0.3s ease;
  }

  .quick-questions-title {
    font-size: 13px;
    color: var(--theme-textSecondary);
    padding: 0 12px 8px 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .refresh-btn {
    font-size: 12px;
    padding: 0;
    height: auto;
    color: var(--theme-textSecondary);
    display: flex;
    align-items: center;
    gap: 4px;
    transition: color 0.3s ease;
  }

  .refresh-btn:hover {
    color: var(--theme-primary);
    background: transparent;
  }

  .refresh-btn .refresh-icon {
    font-size: 12px;
    transition: transform 0.3s ease;
  }

  .refresh-btn:hover .refresh-icon {
    transform: rotate(180deg);
  }

  .quick-questions-list {
    display: flex;
    flex-direction: column;
    max-height: 320px;
    overflow-y: auto;
  }

  .question-item {
    font-size: 14px;
    padding: 8px 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;
    border-left: 2px solid transparent;
  }

  .question-index {
    color: var(--theme-textSecondary);
    font-size: 12px;
    min-width: 20px;
    text-align: center;
    transition: color 0.3s ease;
  }

  .question-text {
    color: var(--theme-text);
    line-height: 1.5;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    transition: color 0.3s ease;
  }

  .question-item:hover {
    background: var(--theme-background);
    border-left-color: var(--theme-primary);
  }

  .question-item:hover .question-text {
    color: var(--theme-primary);
  }

  /* 滚动条样式 */
  .quick-questions-list::-webkit-scrollbar {
    width: 4px;
  }

  .quick-questions-list::-webkit-scrollbar-track {
    background: transparent;
  }

  .quick-questions-list::-webkit-scrollbar-thumb {
    background: var(--theme-border);
    border-radius: 4px;
    transition: background 0.3s ease;
  }

  .quick-questions-list::-webkit-scrollbar-thumb:hover {
    background: var(--theme-primary);
  }

  /* 保持markdown内容紧凑 */
  .markdown-body p {
    margin: 0 !important;
    padding: 0 !important;
    line-height: 1.6;
  }

  .message-content {
    padding: 8px 16px;
    min-height: unset;
    line-height: 1.6;
  }

  .message {
    align-items: flex-start;
  }

  /* AI 消息气泡样式优化 - 确保文字在深色主题下清晰可见 */
  .message-wrapper.assistant .message-text {
    background: var(--theme-surface);
    border: 1px solid var(--theme-border);
    box-shadow: 0 2px 8px var(--theme-shadow);
    font-size: 15px;
    line-height: 1.8;
    color: var(--theme-text) !important;
    font-family:
      -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    letter-spacing: 0.3px;
    transition: all 0.3s ease;
  }

  /* 确保AI消息内容中的文字颜色跟随主题 */
  .message-wrapper.assistant .message-bubble {
    color: var(--theme-text) !important;
  }

  /* 确保markdown内容中的文字颜色跟随主题 */
  .message-wrapper.assistant :deep(.markdown-body) {
    color: var(--theme-text) !important;
  }

  .message-wrapper.assistant :deep(.markdown-body p) {
    color: var(--theme-text) !important;
  }

  .message-wrapper.assistant :deep(.markdown-body h1),
  .message-wrapper.assistant :deep(.markdown-body h2),
  .message-wrapper.assistant :deep(.markdown-body h3),
  .message-wrapper.assistant :deep(.markdown-body h4),
  .message-wrapper.assistant :deep(.markdown-body h5),
  .message-wrapper.assistant :deep(.markdown-body h6) {
    color: var(--theme-text) !important;
  }

  .message-wrapper.assistant :deep(.markdown-body li) {
    color: var(--theme-text) !important;
  }

  .message-wrapper.assistant :deep(.markdown-body blockquote) {
    color: var(--theme-textSecondary) !important;
    border-left-color: var(--theme-primary) !important;
  }

  /* 确保表格文字颜色跟随主题 */
  .message-wrapper.assistant :deep(.markdown-body table th),
  .message-wrapper.assistant :deep(.markdown-body table td) {
    color: var(--theme-text) !important;
  }

  /* 确保代码块中的文字颜色跟随主题 */
  .message-wrapper.assistant :deep(.markdown-body pre) {
    color: var(--theme-text) !important;
  }

  .message-wrapper.assistant :deep(.markdown-body code) {
    color: var(--theme-text) !important;
  }

  /* 消息间距优化 */
  .message-wrapper {
    margin-bottom: 20px;
  }

  /* 链接样式 */
  .markdown-content :deep(a) {
    color: var(--theme-primary);
    text-decoration: none;
    border-bottom: 1px solid transparent;
    transition: border-color 0.3s;
  }

  .markdown-content :deep(a:hover) {
    border-bottom-color: var(--theme-primary);
  }

  /* 表格样式优化 */
  .markdown-content :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 1em 0;
    background: var(--theme-surface);
    transition: background 0.3s ease;
  }

  .markdown-content :deep(th),
  .markdown-content :deep(td) {
    border: 1px solid var(--theme-border);
    padding: 0.6em 1em;
    transition: border-color 0.3s ease;
  }

  .markdown-content :deep(th) {
    background: var(--theme-background);
    font-weight: 600;
    transition: background 0.3s ease;
  }

  /* 水平线样式 */
  .markdown-content :deep(hr) {
    border: none;
    border-top: 1px solid var(--theme-border);
    margin: 1em 0;
    transition: border-color 0.3s ease;
  }

  .ai-think-header {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 6px;
    font-size: 13px;
    color: var(--theme-textSecondary);
    background: var(--theme-background);
    border-radius: 8px 8px 0 0;
    padding: 6px 16px 4px 12px;
    font-weight: 600;
    margin-top: 4px;
    margin-bottom: 2px;
    width: fit-content;
    min-width: 120px;
    transition: all 0.3s ease;
  }
  .ai-think-icon {
    font-size: 15px;
    margin-right: 2px;
  }
  .ai-think-title {
    color: var(--theme-textSecondary);
    font-size: 13px;
    font-weight: 600;
    transition: color 0.3s ease;
  }
  .ai-think-card {
    background: var(--theme-surface);
    color: var(--theme-textSecondary);
    font-size: 13px;
    border-radius: 8px;
    padding: 10px 14px 10px 14px;
    margin-bottom: 4px;
    margin-top: 0;
    line-height: 1.7;
    box-shadow: 0 1px 4px 0 var(--theme-shadow);
    font-family: inherit;
    word-break: break-word;
    transition: all 0.3s ease;
  }
  .ai-think-separator {
    height: 10px;
    width: 100%;
    display: block;
  }
  /* ----------- 代码块美化 ------------- */
  .markdown-content {
    margin: 0 !important;
    padding: 0 !important;
    /* 新增，确保所有绝对定位的子元素（如复制按钮）都限制在内容区 */
    position: relative;
    z-index: 1 !important; /* 明确设置内容层级低于顶部栏 */
  }

  .markdown-content pre {
    background: #23272f !important;
    color: #f8f8f2;
    border-radius: 10px;
    padding: 18px 20px 18px 20px;
    margin: 18px auto;
    max-width: 90%;
    min-width: 0;
    overflow-x: auto;
    font-size: 15px;
    line-height: 1.7;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
    border: 1px solid #22272e;
    position: relative; /* 保证pre内绝对定位元素不会溢出到外部 */
  }
  .markdown-content code {
    background: #f6f8fa !important;
    border-radius: 4px;
    padding: 2px 6px;
    font-size: 15px;
    color: #d6336c;
  }

  .markdown-content pre code {
    background: none !important;
    color: #f8f8f2;
    padding: 0;
    font-size: 15px;
  }

  .markdown-content .hljs {
    background: transparent !important;
    color: #f8f8f2;
    font-family: 'JetBrains Mono', 'Fira Mono', 'Menlo', 'Consolas', 'Liberation Mono', monospace;
  }

  .markdown-content .copy-btn {
    position: absolute;
    top: 10px;
    right: 14px;
    background: rgba(40, 40, 40, 0.7);
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: 2px 10px;
    font-size: 13px;
    cursor: pointer;
    opacity: 0.7;
    transition:
      opacity 0.2s,
      background 0.2s;
    z-index: 2;
  }
  .markdown-content .copy-btn:hover {
    opacity: 1;
    background: #409eff;
    color: #fff;
  }

  .markdown-content {
    margin: 0 !important;
    padding: 0 !important;
  }

  .message-bubble.waiting {
    min-height: 36px;
    padding: 12px 22px;
    border-radius: 18px;
    background: var(--theme-surface);
    box-shadow: 0 2px 12px var(--theme-shadow);
    display: flex;
    align-items: center;
    width: fit-content;
    transition: all 0.3s ease;
  }

  .dot-typing {
    display: flex;
    align-items: center;
    font-size: 22px;
    color: var(--theme-textSecondary);
    letter-spacing: 2px;
    transition: color 0.3s ease;
  }

  .dot-typing span {
    animation: blink 1.4s infinite both;
    margin: 0 1px;
  }

  .dot-typing span:nth-child(2) {
    animation-delay: 0.2s;
  }
  .dot-typing span:nth-child(3) {
    animation-delay: 0.4s;
  }

  @keyframes blink {
    0%,
    80%,
    100% {
      opacity: 0.3;
    }
    40% {
      opacity: 1;
    }
  }

  /* 深色主题特殊处理 */
  [data-theme="dark"] .chat-header {
    background: var(--theme-surface);
  }

  [data-theme="dark"] .chat-footer {
    background: var(--theme-background);
  }

  [data-theme="dark"] .message-bubble {
    background: var(--theme-surface);
  }

  [data-theme="dark"] .message-wrapper.assistant .message-text {
    background: var(--theme-surface);
    color: var(--theme-text) !important;
  }

  [data-theme="dark"] .header-info h2 {
    color: var(--theme-text);
  }

  [data-theme="dark"] .status {
    color: var(--theme-textSecondary);
  }
</style>
